//获取应用实例
const app = getApp();
var _this,util = require('../../utils/util.js');
var stateParams,carClear = false,preventReClick = true; // 是否去匹配维修师
//用户确认配件及费用
var operation_5 = '用户确认了维修方案操作';
//用户确认配件及费用
var operation_4 = '维修工提交了维修方案操作，用户要求重新报价';
//用户确认运费方案   跳转到后台jsp
var operation_7 = '代理商提交了运费方案操作';
//用户确认订单 完成
var operation_14 = '用户确认订单完成操作';
var operation_1 = '取消操作';
/*更改statusId*/
//用户确认配件
var change_status_5 = 5;
//用户重新发起配件
var change_status_4 = 4;
var change_status_3 = 3;
//用户确认运费方案   跳转到后台jsp
var change_status_7 = 10;
//用户确认订单 完成
var change_status_14 = 100;
/*用户取消*/
var change_status_1 = 110;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payload: null,
    sts: null,
    button: null,
    checkStatus: null,
    useFund:false,
    modifyNameFocus:false,
    modifyPhoneFocus:false,
    shopCarBox: false,
    overtimeBox: false,
    buttonClicked: false,
    cancellationOder: false, // 取消订单弹窗
    reasonCancellation: [
      {
        name: '等待时间过长',
        checked: false
      }, {
        name: '订单更改',
        checked: false
      }, {
        name: '服务问题',
        checked: false
      }, {
        name: '临时有事情',
        checked: false
      }, {
        name: '报价问题',
        checked: false
      }, {
        name: '其他原因',
        checked: false
      }
    ],
    preventResubmit: true,  // 选择维修师
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this
    // 获取参数
    stateParams = options;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 支付方式
    var payMethodItems =  [
      { name: '微信支付', value: '微信支付', img:'icon-weixin.png', recommend:'true', checked: 'true' },
      { name: '货到付款', value: '货到付款', img:'icon-hdfk.png'},
    ]
    // 获取参数
    var payload = {
      //初始化为订单状态页
      tab: 0, //默认改为订单详情
      id: stateParams.id ? stateParams.id : null, //订单号
      type: stateParams.type ? stateParams.type : null,// 订单进行状态
      serviceTypeTxt: ['维修', '大保养', '小保养', '换件'],
    }
    if (stateParams.tab){
      payload.tab = stateParams.tab;
    }
    var checkStatus = {
      id: stateParams.id ? stateParams.id : null,
      statusId: null,
      operationType: null,
      operation: null
    }
    
    _this.setData({
      payload: payload,
      checkStatus: checkStatus,
      payMethodItems: payMethodItems, // 支付方式组
      payMethod: '微信支付',  // 默认支付方式
    });
    if (payload.tab == 0) {
      _this.SwitchStatus();
    } else {
      _this.SwitchDetail(function(){
        var payload = _this.data.payload;
        // 判断是否超时
        if (payload.tab == 1 && (payload.serviceType == '2' || payload.serviceType == '1') && payload.statusId == 30 && payload.payTimestampBloon == true) {
          _this.setData({
            overtimeBox: true
          })
        }
        
      });
    }
    // 修改title
    _this.changeTitle(payload);
  },
  changeTitle: function (payload){
    /* 修改标题 */
    if (payload.type == null) {
      wx.setNavigationBarTitle({
        title: '养械订单'
      });
    } else if (payload.type == 'ing') {
      wx.setNavigationBarTitle({
        title: '进行中的养械订单'
      });
    } else if (payload.type == 'done') {
      wx.setNavigationBarTitle({
        title: '已完成的养械订单'
      });
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var tab = _this.data.payload.tab
    wx.showLoading({
      title: '加载中',
    })
    switch (tab) {
      case 0:
        setTimeout(function(){
          _this.SwitchStatus(function () {
            // complete
            wx.hideNavigationBarLoading() //完成停止加载
            wx.stopPullDownRefresh() //停止下拉刷新
          });
          wx.hideLoading();
        },500)
        break;
      case 1:
        setTimeout(function () {
          _this.SwitchDetail(function () {
            // complete
            wx.hideNavigationBarLoading() //完成停止加载
            wx.stopPullDownRefresh() //停止下拉刷新
          });
          wx.hideLoading();
        }, 500)
        
        break;
    }
  },
  // 加载订单状态
  SwitchStatus:function(callback){
    var payload = _this.data.payload;
    payload.tab = 0;
    wx.showLoading({
      title: '加载中',
    })
    _this.setData({
      payload: payload
    })
    _this.mtQueryOrderStatus(function(){
      if (typeof (callback) == 'function') {
        callback();
      }
    });
  },
  // 加载订单详情
  SwitchDetail: function (callback) {
    var payload = _this.data.payload;
    payload.tab = 1;
    wx.showLoading({
      title: '加载中',
    })
    _this.setData({
      payload: payload
    })
    _this.loadReparingByUser(function(){
      if (typeof (callback) == 'function') {
        callback();
      }
    });
    /*请求订单id 对应的购物车信息*/
    //读取购物车
    //$scope.$broadcast('scroll.infiniteScrollComplete');
  },
  // 订单状态轴
  mtQueryOrderStatus:function(callback){
    app.mtQueryOrderStatus(_this.data.payload.id, function (res) {
      // 取消加载中
      wx.hideLoading();
      console.log(res);
      if (res) {
        var button = res.data[res.data.length - 1];
        _this.setData({
          sts: res.data,
          button: button
        })
        if (callback) {
          callback();
        }
        console.log('res', res);
      }
      else {
        //P.alertMsg("错误", "网络异常,请稍后再试");
        //
        if (callback) {
          callback();
        }
      }
    });
  },
  // 加载订单信息
  loadReparingByUser:function(callback){
    var payload = _this.data.payload;
    var checkStatus = _this.data.checkStatus;
    app.querymtNewOrderDetail(payload.id, function (res) {
      if (res) {
        // 取消加载中
        wx.hideLoading();
        console.log('加载订单信息', res);
        _this.reparingByUser(res.data);
        _this.setData({
          useCoupon: res.dataAdd
        })
        if (payload.tab == 1 && payload.serviceType >= '3' && !payload.appointRepairman) {
          let data = {}
          data.id = _this.data.payload.id
          data.serviceType = _this.data.payload.serviceType
          data.date = _this.data.payload.serviceDate
          data.province = _this.data.payload.province
          data.city = _this.data.payload.city
          data.district = _this.data.payload.area
          data.brand = _this.data.payload.brandId
          _this.mtMatching(data);
        }
      } else {
        util.alertMsg('错误', '网络异常,请稍后再试', function () {
          console.log('用户点击确定');
          //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
        }, function () {
          console.log('用户点击取消')
        });
      }
      if (typeof (callback) == 'function') {
        callback();
      }
    });
  },
  reparingByUser:function(res){
    var payload = _this.data.payload;
    var checkStatus = _this.data.checkStatus;
    payload = Object.assign(payload, res);
    console.log('object=', payload);
    // 维修金
    // 默认未超时
    payload.payTimestampBloon = false;
    payload.serviceTimeBegin = res.serviceTimeBegin?res.serviceTimeBegin.split(':')[0] + ':00':'';
    payload.serviceTimeEnd = res.serviceTimeBegin ?res.serviceTimeEnd.split(':')[0] + ':00':'';
    // 支付状态
    payload.payStatus = res.payStatus;
    // 获取时间戳时间
    if (res.payTimestamp){
      var payTimestamp = res.payTimestamp.replace(/-/g, '/');
      var beforeDay = new Date(res.payTimestamp)
      //var beforeDay = res.payTimestamp;
      console.log('beforeDay==', beforeDay);
      // 获取当前时间
      var timeSecond = new Date();
      var intervalsTime = parseInt((timeSecond.getTime() - beforeDay.getTime()) / 1000 / 60 / 60);
      // 判断是否超时
      payload.payTimestampBloon = intervalsTime > 1 ? true : false;
    }
    console.log('$scope.payloadbbbbbbbbbbbbbbbbbbbbbb=', payload);
    _this.setData({
      payload: payload,
      checkStatus: checkStatus,
    })
  },
  // 取消订单
  cancelOrder:function(){
    util.alertMsg('提示', '您确定取消当前订单吗', function () {
      console.log('用户点击确定')
      wx.showLoading({
        title: '加载中',
      })
      // _this.userDetailOperation(change_status_1, '用户取消订单', _this.jumpToApplyServe);
      _this.userDetailOperation(change_status_1, '用户取消订单', function () {
        _this.loadReparingByUser();
      });
    }, function () {
      console.log('用户点击取消')
    });
  },
  // 取消订单跳转
  jumpToApplyServe:function() {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];  //上一个页面
    if (prevPage.SwitchNonPaymen){
      prevPage.SwitchNonPaymen();
      // 返回上一页面
      if (!_this.data.buttonClicked) {
        util.buttonClicked(_this);
        wx.navigateBack({
          delta: 1
        })
      }
    }else{
      if (!_this.data.buttonClicked) {
        util.buttonClicked(_this);
        wx.redirectTo({
          url: '/pages/service-list/service-list'
        })
      }
    }
    
  },
  // 订单完成
  overOrder:function(){
    wx.showLoading({
      title: '加载中',
    })
    var sts = _this.data.sts[_this.data.sts.length - 1].status 
    if (sts == 70){
      //_this.userDetailOperation(change_status_14, operation_14)
      if (!_this.data.buttonClicked) {
        util.buttonClicked(_this);
        wx.navigateTo({
          title: "goback",
          url: '/pages/service-detail/evaluation-order/evaluation-order?statusId=' + change_status_14 + '&remark=' + operation_14 + '&id=' + _this.data.payload.id
        })
      }
    }
    // 取消加载中
    wx.hideLoading();
  },
  // 用户操作切换状态
  userDetailOperation: function (statusId, remark, callback, selfService, commentText, payMode){
    var checkStatus = _this.data.checkStatus;
    checkStatus.statusId = statusId;
    checkStatus.remark = remark;
    if (selfService){
      checkStatus.selfHelp = true;
    }
    payMode ? checkStatus.payMode = payMode : '';
    checkStatus.formId = null;
    // console.log($scope.checkStatus)
    app.mtOperationSwicthStatus(checkStatus, function (rs) {
      // 取消加载中
      wx.hideLoading();
      console.log(rs);
      if (rs) {
        if (rs.status == 'success') {
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 1000
          })
          //渲染页面
          _this.mtQueryOrderStatus(function(){
            var payload = _this.data.payload
            var sts = _this.data.sts
            payload.statusId = sts[sts.length - 1].statusId;
            _this.setData({
              payload: payload
            })
            if (callback) {
              callback();
            }
          });
          app.refreshIndex();
        } else {
          util.alertMsg('错误', rs.message, function () {
            console.log('用户点击确定')
          }, function () {
            console.log('用户点击取消')
          });
        }
      } else {
        util.alertMsg('错误', '网络异常,请稍后再试', function () {
          console.log('用户点击确定')
        }, function () {
          console.log('用户点击取消')
        });
      }
      _this.updatedList();
    });
  },
  // 支付
  goToUserMtPayCenter:function(e){
    var payload = _this.data.payload;
    payload.formId = e.detail.formId;
    if (!_this.data.useFund) {
      payload.repairFundDiscount = 0
    } else {
      payload.repairFundDiscount = payload.repairFundDiscount * 100
    } 55
    // 1、先核算
    app.placeRepairOrder(payload, function (res) {
      if (res.data.status == 'success') {
        app.repairOrderPay(payload.id, function (res) {
          wx.requestPayment({
            'timeStamp': res.timeStamp,
            'nonceStr': res.nonceStr,
            'package': res.package,
            'signType': 'MD5',
            'paySign': res.paySign,
            'success': function (res) {
              console.log('支付成功', res)
              _this.loadReparingByUser();
            },
            'fail': function (res) {
              console.log('支付失败', res)
              _this.loadReparingByUser();
            }
          })
        });
      }
    })
  },
  // 打电话
  makePhoneCall:function(e){
    var phoneNumber = e.target.dataset.phoneNumber ? e.target.dataset.phoneNumber : e.currentTarget.dataset.phoneNumber;
    wx.makePhoneCall({
      phoneNumber: phoneNumber,
    })
  },
  // 维修基金使用开关
  tableUseFund: function (e) {
    var payload = _this.data.payload;
    var useFund = e.detail.value
    if (useFund) {
      payload.totalFeeDiscounted = (payload.totalFee - payload.repairFundDiscount)
    }else{
      payload.totalFeeDiscounted = payload.totalFee
    }
    this.setData({
      useFund: useFund,
      payload: payload
    })
  },
  /*
   * 2018-5-21 
   */
  /*
   * 修改资料
   */
  // 修改姓名按钮
  chooseNameIcon:function(){
    this.setData({
      modifyNameFocus: true
    })
  },
  // 修改手机按钮
  choosePhoneIcon: function () {
    this.setData({
      modifyPhoneFocus: true
    })
  },
  // 修改姓名
  modifyName:function(e){
    // 获取姓名
    var name = e.detail.value
    // 判断是否为空,否提示，返回原值
    if(name == ''|| name == null){
      util.alertMsg('提示', '姓名不能为空', function () {
        console.log('用户点击确定');
        _this.SwitchDetail();
        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');
        _this.SwitchDetail();
      });
      return;
    }
    // 修改资料
    _this.ModifyData(name);
    // 关闭修改
    _this.setData({
      modifyNameFocus: false
    })
  },
  // 修改电话
  modifyPhone:function(e){
    // 获取电话
    var phone = e.detail.value
    if (phone == null || phone == '') {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '您的联系电话输入有误，请重新修改', function () {
        _this.SwitchDetail();
      }, function () {
        _this.SwitchDetail();
      });
      return;
      /*验证手机号*/
    }
    var isPhone = false;
    util.testPhone(phone, function (rs) {
      if (rs) {
        isPhone = true;
      } else {
        isPhone = false;
      }
    });
    if (!isPhone) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '您的联系电话输入有误，请重新修改', function () {
        _this.SwitchDetail();
      }, function () {
        _this.SwitchDetail();
      });
      return;
    }
    // 修改资料
    _this.ModifyData(null, phone);
    // 关闭修改
    _this.setData({
      modifyNameFocus: false
    })
  },
  // 提交修改
  ModifyData:function(name, phone){
    var data = {};
    var payload = _this.data.payload;
    data.id = payload.id
    data.contact = name;
    data.contactPhone = phone;
    app.repairOrderModify(data,function(res){
      if (res.status == "success"){
        console.log("success");
      }else{
        util.alertMsg('提示', '修改失败，请稍后再试', function () {
          _this.SwitchDetail();
        }, function () {
          _this.SwitchDetail();
        });
      }
    })
  },
  /*
   *超时
  */
  // 继续等待
  keepWaiting: function(){
    var id = _this.data.payload.id;
    app.keepWaiting(id, function(res){
      console.log(res);
      _this.setData({
        overtimeBox:false
      })
    })
    wx.showToast({
      title: '提交成功请耐心等待',
      icon: 'success',
      duration: 1000
    })
  },
  // 超时取消订单
  timeOutCancelOrder:function(){
    util.alertMsg('提示', '您已取消该订单，退款将在24小时内完成，请注意查看；', function () {
      wx.showLoading({
        title: '加载中',
      })
      //_this.userDetailOperation(change_status_1, '用户取消订单', _this.jumpToApplyServe);
      _this.userDetailOperation(change_status_1, '用户取消订单', function(){
        //_this.loadReparingByUser();
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];  //上一个页面
        prevPage.init();
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.navigateBack({
            delta: 1,
          })
        }
      });
    }, function () {
      
      console.log('取消取消订单');
    });
  },
  // 自己保养
  selfService:function(){
    _this.userDetailOperation(change_status_14, null,function(){
      _this.loadReparingByUser();
    }, true);
  },
  // 展开收缩商品列表
  shopCarBoxFun:function(){
    var shopCarBox = _this.data.shopCarBox;
    _this.setData({
      shopCarBox: !shopCarBox
    })
  },
  // 更新列表页信息
  updatedList:function(){
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];  //上一个页面
    if (prevPage.SwitchNonPaymen){
      switch (prevPage.data.tab){
        case 0:
          prevPage.SwitchNonPaymen();
          break;
        case 1:
          prevPage.SwitchIng();
          break;
        case 2:
          prevPage.SwitchComplete();
          break;
      }
    }
  },
  // 我的优惠券
  myCoupon:function(){
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/my-coupon/my-coupon?useCoupon=true'
      })
    }
  },
  // 关闭超时
  clooseOvertime:function(){
    _this.setData({
      overtimeBox:false
    })
  },
  // mtMatching:function(){
  //   if (!_this.data.buttonClicked) {
  //     util.buttonClicked(_this);
  //     wx.navigateTo({
  //       url: '/pages/choose-repairman/choose-repairman?id=' + _this.data.payload.id
  //     })
  //   }
  // },
  // 取消订单
  reasonCancellationFun:function(e){
    var reasonCancellationValue = e.detail.value;
    _this.setData({
      reasonCancellationValue: reasonCancellationValue
    })
  },
  checkedChoose:function(e){
    var index = e.currentTarget.dataset.id
    var reasonCancellation = _this.data.reasonCancellation;
    reasonCancellation[index].checked = !reasonCancellation[index].checked;
    _this.setData({
      reasonCancellation: reasonCancellation
    })
  },
  // 取消订单Tow
  cancelOrderTow: function (e) {
    var reasonCancellation, checkbox = e.detail.value.checkbox, textarea = e.detail.value.textarea
    checkbox = checkbox.join('、');
    reasonCancellation = checkbox + '、' + textarea;
    wx.showLoading({
      title: '加载中',
    })
    // statusId, remark, callback, selfService, commentText
    _this.userDetailOperation(change_status_1, reasonCancellation, function () {
      _this.loadReparingByUser();
      _this.setData({
        cancellationOder: false
      })
    });
  },
  cancellationOderClose:function(){
    _this.setData({
      cancellationOder: false
    })
  },
  cancellationOderOpen: function () {
    _this.setData({
      cancellationOder: true
    })
  },
  /*
  * 2018-11-5
  */
  // 支付方式
  payMethodFun: function (e) {
    _this.setData({
      payMethod: e.detail.value
    })
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },
  // 确认订单按钮
  sureOder: function(e){
    let payMethod = _this.data.payMethod;
    if (payMethod == '微信支付'){
      _this.goToUserMtPayCenter(e);
    } else if (payMethod == '货到付款'){
      _this.userDetailOperation(30, '货到付款', function () {
        _this.loadReparingByUser();
      }, null, null, payMethod);
    }
  },
  // 匹配维修师
  mtMatching: function (id) {
    app.mtMatching(id, 1, 1000, function (res) {
      if (res) {
        _this.setData({
          repairmanList: res.data.results
        })
        // 更新维修师列表 app 
        app.globalData.repairmanList = res.data.results;
        // 取消加载中
        wx.hideLoading();
        console.log(res);
      } else {
        util.alertMsg('提示', '获取维修师列表失败，请稍后再试。', function () {
          if (!_this.data.buttonClicked) {
            util.buttonClicked(_this);
            wx.reLaunch({
              url: '/pages/index/index',
            })
          }
          return;
        }, function () {
          if (!_this.data.buttonClicked) {
            util.buttonClicked(_this);
            wx.reLaunch({
              url: '/pages/index/index',
            })
          }
          return;
        });
      }
    })
  },
  // 维修师详情
  repairmanIntro: function (e) {
    var index = e.currentTarget.dataset.index // 序号
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/repairman-intro/repairman-intro?oderId=' + _this.data.payload.id + '&index=' + index + '&preventResubmit=' + _this.data.preventResubmit
      });
    }
  },
  // 选择维修师
  chooseRepairman: function (e) {
    var payload = {}, data = {};
    payload.id = _this.data.payload.id;
    payload.repairmanCode = e.currentTarget.dataset.repairmanCode;
    let index = e.currentTarget.dataset.index,
      repairmanList = _this.data.repairmanList[index]

    data.checkFee = repairmanList.checkFee;
    data.productFee = repairmanList.productFee;
    data.serviceFee = repairmanList.serviceFee;
    data.totalFee = repairmanList.totalFee;
    data.trafficFee = repairmanList.trafficFee;
    if (_this.data.preventResubmit) {
      _this.setData({
        preventResubmit: false
      })
      app.mtChooseMaintenance(payload, function (res) {
        if (res) {
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 1500,
            mask: true,
            success: function () {
              _this.SwitchDetail();
            }
          })
        } else {
          util.alertMsg('提示', '选择维修师失败，请稍后再试。', function () {
            _this.SwitchDetail();
            return;
          }, function () {
            _this.SwitchDetail();
            return;
          });
        }
      },data)
    } else {
      util.alertMsg('提示', '不能重复提交', function () {
        _this.SwitchDetail();
        return;
      }, function () {
        _this.SwitchDetail();
        return;
      });
    }
  },
  // 打电话
  makePhoneCall: function (e) {
    var phoneNumber = e.currentTarget.dataset.phoneNumber;
    wx.makePhoneCall({
      phoneNumber: phoneNumber,
    })
  },
  // 开关
  toggleSwitch: function (e) {
    let name = e.currentTarget.dataset.name;
    let value = !_this.data[name]
    _this.setData({
      [name]: value
    })
  },
})

